//
//  ScrollViewTest.swift
//  图片裁剪器
//
//  Created by linhan on 14-11-17.
//  Copyright (c) 2014年 linhan. All rights reserved.
//

import Foundation
import UIKit

@objc protocol SWImageCropperDelegate:NSObjectProtocol
{
    func imageCropperViewController(viewController:SWImageCropperViewController, didFinishCroppingImage croppedImage:UIImage)
}

class SWImageCropperViewController:SWBaseViewController,UIScrollViewDelegate
{
    weak var delegate:SWImageCropperDelegate?
    
    private var _scrollView:UIScrollView = UIScrollView()
    
    private var _imageView:UIImageView = UIImageView()
    
    private var _containerView:UIView = UIView()
    
    //辅助线
    private var _auxiliaryLineView:UIView = UIView()
    
    private var _originImage:UIImage
    
    private var contentInsets:UIEdgeInsets = UIEdgeInsetsZero
    
    init(image:UIImage)
    {
        _originImage = image
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        trace("DEINIT SWImageCropperViewController")
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.black
        
        
        let Edge:CGFloat = view.width
        _scrollView.frame = CGRectMake(0, floor((view.height - Edge) * 0.5), Edge, Edge)
        _scrollView.backgroundColor = UIColor.white
        _scrollView.delegate = self
        _scrollView.minimumZoomScale = 0.1
        _scrollView.maximumZoomScale = 1.5
        _scrollView.clipsToBounds = false
        _scrollView.showsHorizontalScrollIndicator = false
        _scrollView.showsVerticalScrollIndicator = false
        view.addSubview(_scrollView)
        drawMaskShape(_scrollView.frame)
        auxiliaryLineViewSetup()
        
        //contentInsets = UIEdgeInsetsMake(Edge - 20, Edge - 20, Edge - 20, Edge - 20)
        
        _containerView.addSubview(_imageView)
        _scrollView.addSubview(_containerView)
        
        
        var image:UIImage = _originImage
        var imageWidth:CGFloat = image.size.width
        var imageHeight:CGFloat = image.size.height
        //先将巨大的原图缩小，以提供流畅度
        var scale:CGFloat = ViewUtil.getAdaptiveScale(imageWidth, targetH: imageHeight, containerW: _scrollView.width * 2, containerH: _scrollView.height * 2, inscribed: false)
        if scale < 1
        {
            image = Toucan.Resize.resizeImage(image, size: CGSizeMake(imageWidth * scale, imageHeight * scale), fitMode:.Scale)
        }
        imageWidth = image.size.width
        imageHeight = image.size.height
        _imageView.image = image
        
        scale = ViewUtil.getAdaptiveScale(imageWidth, targetH: imageHeight, containerW: _scrollView.width, containerH: _scrollView.height, inscribed: false)
        imageWidth = imageWidth * scale
        imageHeight = imageHeight * scale
        _imageView.frame = CGRectMake(contentInsets.left, contentInsets.top, imageWidth, imageHeight)
        
        let newWidth:CGFloat = contentInsets.left + imageWidth + contentInsets.right
        let newHeight:CGFloat = contentInsets.top + imageHeight + contentInsets.bottom
        
        _containerView.frame = CGRectMake(0, 0, newWidth, newHeight)
        
        _scrollView.contentSize = CGSizeMake(newWidth, newHeight)
        _scrollView.contentOffset = CGPointMake(contentInsets.left - (_scrollView.width - imageWidth) * 0.5, contentInsets.top - (_scrollView.height - imageHeight) * 0.5)
        
        let BottomViewHeight:CGFloat = 48
        let bottomView:UIView = UIView()
        bottomView.backgroundColor = UIColor.white
        bottomView.frame = CGRectMake(0, view.height - BottomViewHeight, view.width, BottomViewHeight)
        view.addSubview(bottomView)
        
        let cropBtn:UIButton = UIButton(type:.system)
        cropBtn.setTitleColor(SWAppearanceManager.themeStyle.majorTitleColor, for: .normal)
        cropBtn.setTitle("使用", for: .normal)
        cropBtn.sizeToFit()
        cropBtn.frame = CGRectMake(bottomView.width - cropBtn.width - 25, 0, cropBtn.width, bottomView.height)
        cropBtn.addTarget(self, action: #selector(cropBtnTapped(_:)), for: .touchUpInside)
        bottomView.addSubview(cropBtn)
        
        let cancelBtn:UIButton = UIButton(type:.system)
        cancelBtn.setTitleColor(SWAppearanceManager.themeStyle.majorTitleColor, for: .normal)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.sizeToFit()
        cancelBtn.frame = CGRectMake(25, 0, cancelBtn.width, bottomView.height)
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        bottomView.addSubview(cancelBtn)
    }
    
    //绘制中间镂空的遮罩
    private func drawMaskShape(cropRect:CGRect)
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0);
        if let context:CGContextRef = UIGraphicsGetCurrentContext()!
        {
            //半透明遮罩
            UIColor(white:0, alpha:0.6).setFill()
            UIRectFill(self.view.bounds)
            
            //方法1：直接清除区域
            CGContextClearRect(context, cropRect);
            
            let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            let imageView:UIImageView = UIImageView(image:image)
            view.addSubview(imageView)
        }
    }
    
    private func auxiliaryLineViewSetup()
    {
        let ContainerWidth:CGFloat = _scrollView.width
        let ContainerHeight:CGFloat = _scrollView.height
        let LineWidth:CGFloat =  ContainerWidth - 1
        let LineHeight:CGFloat =  ContainerHeight - 1
        
        
        let color:UIColor = UIColor(hex:0xd6dfeb)
        let hLine1:UIView = UIView(frame: CGRectMake(0.5, ContainerHeight / 3, LineWidth, 0.5))
        hLine1.backgroundColor = color
        let hLine2:UIView = UIView(frame: CGRectMake(0.5, ContainerHeight * 2 / 3, LineWidth, 0.5))
        hLine2.backgroundColor = color
        
        let vLine1:UIView = UIView(frame: CGRectMake(ContainerWidth / 3, 0.5, 0.5, LineHeight))
        vLine1.backgroundColor = color
        let vLine2:UIView = UIView(frame: CGRectMake(ContainerWidth * 2 / 3, 0.5, 0.5, LineHeight))
        vLine2.backgroundColor = color
        
        _auxiliaryLineView.addSubview(hLine1)
        _auxiliaryLineView.addSubview(hLine2)
        _auxiliaryLineView.addSubview(vLine1)
        _auxiliaryLineView.addSubview(vLine2)
        _auxiliaryLineView.frame = _scrollView.frame
        _auxiliaryLineView.userInteractionEnabled = false
        //_auxiliaryLineView.hidden = true
        view.addSubview(_auxiliaryLineView)
        
        let borderView:UIView = UIView()
        borderView.frame = _scrollView.frame
        borderView.layer.borderColor = color.CGColor
        borderView.layer.borderWidth = 0.5
        borderView.userInteractionEnabled = false
        view.addSubview(borderView)
    }
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
    {
        return _containerView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat)
    {
        let globalX:CGFloat = _imageView.x * scale - _scrollView.contentOffset.x
        let globalY:CGFloat = _imageView.y * scale - _scrollView.contentOffset.y
        let imageWidth = _imageView.width * scale
        let imageHeight = _imageView.height * scale
        _imageView.frame = CGRectMake(contentInsets.left, contentInsets.top, imageWidth, imageHeight)
        _scrollView.zoomScale = 1
        
        let newWidth:CGFloat = contentInsets.left + imageWidth + contentInsets.right
        let newHeight:CGFloat = contentInsets.top + imageHeight + contentInsets.bottom
        
        _containerView.frame = CGRectMake(0, 0, newWidth, newHeight)
        
        _scrollView.contentOffset = CGPointMake(_imageView.x - globalX, _imageView.y - globalY)
        _scrollView.contentSize = CGSizeMake(newWidth, newHeight)
        //_auxiliaryLineView.hidden = true
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView)
    {
        //_auxiliaryLineView.hidden = false
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool)
    {
        //_auxiliaryLineView.hidden = true
    }
    
    private func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func cropBtnTapped(_ button:UIButton)
    {
        //scrollview中的图片是缩小版的，便于流畅拖拽；最后生成的缩小版对原图进行裁剪
        let xPercent:CGFloat = (contentInsets.left - _scrollView.contentOffset.x) / _scrollView.width
        let yPercent:CGFloat = (contentInsets.top - _scrollView.contentOffset.y) / _scrollView.height
        let widthPercent:CGFloat = _imageView.width / _scrollView.width
        let heightPercent:CGFloat = _imageView.height / _scrollView.height
        
        let TemplateSize = SW.Config.ProcessImagePresetSize
        let rect:CGRect = CGRectMake(TemplateSize.width * xPercent, TemplateSize.height * yPercent, TemplateSize.width * widthPercent, TemplateSize.height * heightPercent)
        
        SVProgressHUD.showWithStatus("处理中...")
        button.enabled = false
        DispatchQueue.global(priority: .default).async(execute: {
                UIGraphicsBeginImageContextWithOptions(TemplateSize, false, 0)
                UIColor.white.setFill()
                UIRectFill(CGRectMake(0, 0, TemplateSize.width, TemplateSize.height))
                
                self._originImage.drawInRect(rect)
                let image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                DispatchQueue.main.async{
                    button.enabled = true
                    SVProgressHUD.dismiss()
                    self.delegate?.imageCropperViewController(self, didFinishCroppingImage: image)
                    self.close()
                }
        })
        
    }
    
    @objc private func cancelBtnTapped()
    {
        close()
    }
    
    
    
    
}
